//
//  RegetButton.m
//
//
//  Created by  on 14-12-14.
//
//

#import "RegetButton.h"
#import "StringUtil.h"

@implementation RegetButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        orgTitle = @"获取验证码";
        [self setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    
    return self;
}

- (void)timerExpired
{
    remainSeconds--;
    if(remainSeconds == 0)
    {
        [self stopTimer];
    }
    else
    {
        [self setTitle:[NSString stringWithFormat:@"%d秒", remainSeconds] forState:UIControlStateNormal];
    }
}

- (void)startTimer:(NSUInteger)seconds
{
    orgTitle = [self titleForState:UIControlStateNormal];
    [self setTitle:@"" forState:UIControlStateNormal];
    
    self.enabled = NO;
    self.titleLabel.hidden = YES;
    remainSeconds = seconds;
    [self setTitle:[NSString stringWithFormat:@"%d秒", remainSeconds] forState:UIControlStateNormal];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerExpired) userInfo:nil repeats:YES];
}

- (void)stopTimer
{
    orgTitle = @"重新获取验证码";
    [self setTitle:orgTitle forState:UIControlStateNormal];
    
    if([timer isValid])
    {
        [timer invalidate];
        timer = nil;
    }
    self.enabled = YES;
    self.titleLabel.hidden = NO;
}

@end
